package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.dto.ArticleDto;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-30
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {


    @Autowired
    private IApArticleContentService apArticleContentService;
    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
        // 判断是否是更新
        if (dto.getId() == null){
            apArticle.setCreatedTime(new Date());
            // 保存文章
            this.save(apArticle);
            // 保存文章内容
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(apArticle.getId());
            content.setContent(dto.getContent());
            apArticleContentService.save(content);
            // 返回通用响应
            return ResponseResult.okResult(apArticle.getId());
        }
        // 更新文章
        this.updateById(apArticle);
        // 更新文章内容
        LambdaUpdateWrapper<ApArticleContent> update = new LambdaUpdateWrapper<>();
        update.eq(ApArticleContent::getArticleId,dto.getId());
        update.set(ApArticleContent::getContent,dto.getContent());
        apArticleContentService.update(update);
        return ResponseResult.okResult(dto.getId());
    }
}
